package org.trade.web.simple;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * 异步生产：用户实现异步发送回调接口（sendCallback），在执行消息的异步发送的时候不需要等待服务器回应即可直接返回。
 * 异步发生一般用于链路耗时时较长，对RT响应时间较为敏感的业务场景。例如用户视频上传后通知转码服务，转码完成后通知推送转码结果等
 * http://blog.csdn.net/u013160932/article/details/58215538
 */
public class AsyncProducer {
	public static void main(String[] args) {
		DefaultMQProducer producer = new DefaultMQProducer("asyn_prducer");
		producer.setNamesrvAddr("106.14.154.169:9876");
		producer.setInstanceName("Producer");
		producer.setVipChannelEnabled(false);
		
		try {
			producer.start();
			producer.setRetryTimesWhenSendAsyncFailed(0);
			for (int i = 0; i < 1; i++) {
				final int index = 1;
				Message msg = new Message("TopicTest", "TagFang", "orderID111",
						"Hello World".getBytes(RemotingHelper.DEFAULT_CHARSET));
				// sendCallback异步
				producer.send(msg, new SendCallback() {
					// 发送成功
					public void onSuccess(SendResult sendResult) {
						System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
					}

					public void onException(Throwable e) {
						System.out.printf("%-10d Exception %s %n", index, e);
						e.printStackTrace();
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		producer.shutdown();
	}
}
